#!/usr/bin/env python
from tempfile import mkstemp
from shutil import move
from os import remove, close
from os import system
def replace(file_path, pattern, subst,count):
    #Create temp file
    fh, abs_path = mkstemp()
    new_file = open(abs_path,'w')
    old_file = open(file_path)
    print(old_file)
    for line in old_file:
        new_file.write(line.replace(pattern, subst,count))
    #close temp file
    new_file.close()
    close(fh)
    old_file.close()
    #Remove original file
    remove(file_path)
    #Move new file
    move(abs_path, file_path)

#import fileinput
#import sys
#def replaceAll(file,searchExp,replaceExp,count):
#    for line in fileinput.input(file, inplace=1):
#        if searchExp in line:
#            line = line.replace(searchExp,replaceExp,count)
#        sys.stdout.write(line)

import os

def genEe(file_path):
  """
  only one file is supported
  file_path is the path include file name itself.
  """
  print(file_path)
  if os.path.exists("tags"):
    print("clean exist tags, and regenerte new tags for dedicate file:",file_path)
    os.remove("tags")
    ctags4eCmd = "ctags4e "+file_path
    os.system(ctags4eCmd)
    print("change relative tags to global tags")
    absPath = os.path.abspath(file_path)
    print(absPath)
    replace("tags",file_path,absPath,1)
    print("done *_*")
  else:
    print("no tags found, just generte new tags")
    ctags4eCmd = "ctags4e "+file_path
    os.system(ctags4eCmd)
    print("change relative tags to global tags")
    absPath = os.path.abspath(file_path)
    replace("tags",file_path,absPath,1)
    print("done *_*")

if __name__ == "__main__":
  import sys
  genEe(str(sys.argv[1]))

